import models.db as db
from flask import request,  jsonify


# 用户列表展示
def users_view():
    message = request.get_json()
    sql = "select * from users where name like @name"
    p = "%"+message["msg"]+"%"
    rows = db.get_db(sql, (p,))
    rows = [dict(row) for row in rows]
    return jsonify({"userlist": rows, "meta": {'status': '200', 'msg': '用户列表获取成功！'}})


# 添加用户
def users_add():
    message = request.get_json()
    message_data = []
    sum_data = []
    for i in message.values():
        message_data.append(i)
    sum_data.append(tuple(message_data))
    sql = "insert into users (name, password, email, mobile, role_name) values (?, ?, ?, ?, ?)"
    db.query_db(sql, sum_data)
    return jsonify({'status': '200', 'msg': '创建成功！'})


# 删除用户
def users_drop():
    message = request.get_json()
    num = message['user_id']
    print(num)
    sql = "delete from users where user_id = ?"
    db.get_db(sql, (num,))
    return jsonify({'status': '200', 'msg': '删除成功！'})


# 打开编辑用户
def users_edit_open():
    message = request.get_json()
    num = message['user_id']
    print(num)
    sql = "select name,email,mobile from users where user_id = ?"
    rows = db.get_db(sql, (num,))
    rows = [dict(row) for row in rows]
    return jsonify(rows)


# 编辑用户
def users_edit():
    message = request.get_json()
    print(message)
    message_data = []
    sum_data = []
    for i in message.values():
        message_data.append(i)
    sum_data.append(tuple(message_data))
    sql = "update users set email=?, mobile=? where name=?"
    db.query_db(sql, sum_data)
    return jsonify({'status': '200', 'msg': '修改成功！'})


# 分配角色展开
def users_give_open():
    message = request.get_json()
    num = message['user_id']
    sql = "select * from users where user_id = ?"
    rows = db.get_db(sql, (num,))
    rows = [dict(row) for row in rows]
    return jsonify(rows)


# 修改角色
def users_editrole():
    message = request.get_json()
    print(message)
    user_id = message['user_id']
    role_name = message['role_name']
    sql = "update users set role_name= ? where user_id = ?"
    db.get_db(sql, (role_name, user_id,))
    return jsonify({'status': '200', 'msg': '分配角色成功！'})
